// 用户相关控制器
// 导入ip
let { ip, port, level } = require('../config');
// 导入加密模块
let bcryptjs = require('bcryptjs')
// 导入token
let { createToken } = require('../utils/token')
// 导入用户表模型中的方法操作数据
let { findBycond, insertOne, updateOne,delOne } = require('../model/user')
// 导入邮件发送函数
let sendmail = require('../utils/sendEmail');
// 注册控制器
let registerCofn = async (req, res, next) => {
  // 获取注册数据
  let { username, pwd, rpwd, email } = req.body;
  // 两次密码一致性校验
  if (pwd != rpwd) return res.send({ code: 0, message: '两次密码必须一致' })

  // 注意: 所有的数据库操作方法都在模型中
  // 根据用户名查询user数据表,判断是否已注册
  let r1 = await findBycond({ username });
  // 判断r是否有值
  if (r1.length) return res.send({ code: 0, message: '用户已存在,请更换重试!' });

  // 根据邮箱查询user数据表,判断是否已注册
  let r2 = await findBycond({ email });
  // 判断r是否有值
  if (r2.length) return res.send({ code: 0, message: '邮箱已存注册,请更换重试!' });

  // 将用户信息写入到user表 完成注册
  // 密码加密
  pwd = bcryptjs.hashSync(pwd, level);
  let r3 = await insertOne({ username, pwd, email, createTime: new Date() })
  // 判断r3.status是否为0
  if (r3.status === 0) return next({ code: 0, message: '注册失败,请重试' + r3.message })

  // console.log(r3[0]['_id'])  
  // 注册成功则发送邮件
  let subject = '欢迎加入2308大家庭';
  let emailContent = `
    <p>你好，欢迎来到2308大家庭。</p>

    <p>请点击下面的链接以激活帐号:</p>

    <p>http://${ip}:${port}/user/verify?uid=${r3[0]['_id']}</p>

    <p>如非本人操作，请忽略该邮件</p>

    <p>如果您有任何问题，请通过以下方式联系我们。</p>
    <p>在线客服 | 邮箱 123456@qq.com | 电话 123-456-789</p>
  `
  let r4 = await sendmail(email, subject, emailContent);

  // 判断邮件是否发送成功
  if (r4.status != 1) return res.send({ code: 1, message: '注册成功,请求联系管理员激活账号' })
  res.send({ code: 1, message: '注册成功,请求立即在点击邮件链接激活账号' })
}

// 激活账号控制器
let verifyCofn = async (req, res) => {
  // 获取到用户id
  let _id = req.query.uid;
  let r1 = await findBycond({ _id });
  // 判断r是否有值
  if (!r1.length) return res.send({ code: 0, message: '激活失败,请重试' });

  //激活账号,修改用户数据的flag
  let r2 = await updateOne({ _id }, { flag: 1 });
  // console.log(r2.modifiedCount);
  if (!r2.modifiedCount) return res.send({ code: 0, message: '激活失败,请重试' });
  res.send({ code: 1, message: '激活成功' });
}

// 登录控制器
let loginCofn = async (req, res) => {
  let { name, pwd } = req.body;

  // 根据name查找----name是用户名或邮箱
  let r1 = await findBycond({ $or: [{ username: name }, { email: name }], flag: 1 })
  if (!r1.length) return res.send({ code: 0, message: '用户名或邮箱不存在' });

  // 密码比对
  if (!bcryptjs.compareSync(pwd, r1[0].pwd)) return res.send({ code: 0, message: '用户名/邮箱 或密码错误' });

  // console.log(r1)
  //生成token
  let token = createToken({ id: r1[0]['_id'] })

  // 登录成功
  res.send({ code: 1, message: '登录成功', token, info: { id: r1[0]['_id'], role: r1[0].role, avator: r1[0].avator, age: r1[0].age, gender: r1[0].gender, email: r1[0].email } })
}

// 用户详情控制器
let infoCofn = async (req, res) => {
  let _id = req.query.id
  // 根据id获取用户数据
  let r = await findBycond({ _id, flag: 1 });
  if (!r.length) return res.send({ code: 0, message: '获取失败,请重试' });
  // 响应用户数据
  res.send({
    code: 1, message: '获取用户详情成功', info: {
      id: _id,
      username: r[0].username,
      email: r[0].email,
      gender: r[0].gender,
      age: r[0].age,
      avator: r[0].avator,
      createTime: r[0].createTime,
      tel: r[0].tel,
      role: r[0].role,
    }
  })
}

//修改密码
let pwdCofn = async (req, res) => {
  // 获取数据
  let { oldpwd, newpwd, rnewpwd, id } = req.body;
  // 密码一致性校验
  if (newpwd != rnewpwd) return res.send({ code: 0, message: '两次密码不一致' });
  // 根据id获取用户数据
  let r1 = await findBycond({ _id: id, flag: 1 });
  if (!r1.length) return res.send({ code: 0, message: '修改失败,请重试' });
  // 比对密码
  // 密码比对
  if (!bcryptjs.compareSync(oldpwd, r1[0].pwd)) return res.send({ code: 0, message: '原密码错误' });
  // 密码加密
  pwd = bcryptjs.hashSync(newpwd, level);

  // 修改密码
  let r2 = await updateOne({ _id: id, flag: 1 }, { pwd });
  if (!r2.modifiedCount) return res.send({ code: 0, message: '修改失败,请重试' });
  res.send({ code: 1, message: '修改成功' });
}
// 修改个人信息
let rinfoCofn = async (req, res, next) => {
  let { id, gender, age, tel } = req.body;
  let avator = req.file?.filename;

  let upData = {}; //修改数据
  //  判断用户是否传递 该参数,如果传递则添加到修改数据对象中
  if (gender) upData.gender = gender;
  if (age) upData.age = age;
  if (tel) upData.tel = tel;
  if (avator) upData.avator = avator;
  // console.log(upData);
  // 修改数据
  let r = await updateOne({ _id: id, flag: 1 }, upData);
  if (!r.modifiedCount) return next({ code: 0, message: '修改失败,请重试' });
  res.send({ code: 1, message: '修改成功' });

}


// 后台使用的
let listCon = async (req, res) => {
  // let r = await findAll();
  let r = await findBycond({});
  res.send({ code: 1, list: r, message: '获取成功' })
}

let searchCon = async (req, res) => {
  let { search } = req.query;
  let searchObj = search ? { username: new RegExp(search, 'i') } : {};
  let r = await findBycond(searchObj);
  res.send({ code: 1, list: r, message: '获取成功' })
}

let updateCon = async (req, res) => {
  let { uid, opt, val } = req.body;
  // opt是 'flag'则修改禁用状态,是reset则重置密码 ---> 充值后的密码统一为123456
  val = opt == 'flag' ? val : bcryptjs.hashSync('123456', level);
  opt = opt === 'flag' ? 'flag' : 'pwd'
  let setObj = { [opt]: val };  
  let r2 = await updateOne({ _id: uid }, setObj);
  if (!r2.modifiedCount) return res.send({ code: 0, message: '修改失败,请重试' });
  res.send({ code: 1, message: '修改成功' });
}

let delCon = async (req, res) => {
  let { uid } = req.body
  await delOne(uid);
  res.send({ code: 1, message: '删除成功' });
}




module.exports = {
  registerCofn, verifyCofn, loginCofn, infoCofn, pwdCofn, rinfoCofn, listCon, searchCon, updateCon, delCon
}